import re
import os

def to_number(s):
    try:
        return float(s)
    except ValueError:
        pass

    try:
        return int(s)
    except ValueError:
        pass

    return s


def importIni(path) -> dict:
    ini_data = {'objs' : []}
    filename,dirname = os.path.splitext(os.path.basename(path))
    ini_data['_type'] = filename
    try:
        with open(path,'r',encoding='utf-8') as fi:
            _bytes = fi.read()
    except FileNotFoundError:
        print('错误的ini路径')
        
    cuts = re.findall("\[[\"']?.{4}[\"']?\]\s+",_bytes)
    cuts.reverse()
    _list = []
    for cut in cuts:
        _list.append(_bytes[_bytes.rfind(cut):])
        _bytes = _bytes[:_bytes.rfind(cut)]
    _list.reverse()
    for _str in _list:
        _dict = {}
        _dict['id'] = re.search("\[[\"']?(.{4})[\"']?\]",_str,re.M).groups()[0]
        for key in re.findall("(\w+)\s?=",_str):
            # int string list
            r_str = _str[_str.find(key):]
            r_str = r_str[r_str.find('=')+1:].lstrip()
            key = key.lower()
            if r_str[:1] == "\"":
                exec("_dict[key] = %s" % (r_str[:r_str.find("\"",1)+1]))
            elif r_str[:1] == "'":
                exec("_dict[key] = %s" % (r_str[:r_str.find("'",1)+1]))
            elif r_str[:1] == "{":
                r_str = re.sub('\n','',r_str[1:r_str.find("}")])
                exec("_dict[key] = [%s]" % (r_str))
            else:
                exec("_dict[key] = %s" % (r_str[:r_str.find("\n")]))
        ini_data['objs'].append(_dict)
    return ini_data


if __name__ == "__main__":
    _dicts = importIni(r'E:\Work_War3\War3MoeHero\MoeHero-master\MoeHero-master\logic_test\table\destructable.ini')
    _list = []
    for obj in _dicts['objs']:

        _list.append((obj['id'],obj['name']))

    def takeSecond(elem):
        return elem[1]
    _list.sort(key=takeSecond)

    _str = ''
    for _tu in _list:
        _str += "%s=\t\"%s\",\n"%(_tu[0],_tu[1])
    with open('_test.txt','w',encoding='utf-8')as fi:
        fi.write(_str)
